package com.bw.lib_common.livedata_eventbuss

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData

/**
 * @author ytx
 * @date 2025-09-19 15:57
 * @description
 */
object LiveEventBus {
    // 存储所有事件的总线
    private val eventMap = mutableMapOf<String, Event<*>>()

    @Synchronized
    fun <T> with(eventName: String, isSticky: Boolean = false): Event<T> {
        var event = eventMap[eventName]
        if (event == null) {
            event = Event<T>(eventName, isSticky)
            eventMap[eventName] = event
        }
        return event as Event<T>
    }

    class Event<T>(private val eventName: String, private val isSticky: Boolean) {
        // 使用LiveData作为事件载体
        private val liveData = MutableLiveData<EventWrapper<T>>()

        // 存储粘性事件的值
        private var stickyValue: EventWrapper<T>? = null

        init {
            if (isSticky) {
                liveData.observeForever {
                    if (it != null && !it.isConsumed) {
                        stickyValue = it
                    }
                }
            }
        }

        // 发送事件
        fun post(value: T) {
            val wrapper = EventWrapper(value, isSticky)
            if (isSticky) {
                stickyValue = wrapper
            }
            liveData.postValue(wrapper)
        }

        // 观察事件（非粘性）
        fun observe(owner: LifecycleOwner, observer: (T) -> Unit) {
            liveData.observe(owner) { wrapper ->
                wrapper?.takeIf { !it.isConsumed }?.let {
                    observer(it.value)
                    it.isConsumed = true
                }
            }
        }

        // 观察事件（粘性）
        fun observeSticky(owner: LifecycleOwner, observer: (T) -> Unit) {
            stickyValue?.let {
                if (!it.isConsumed) {
                    observer(it.value)
                    it.isConsumed = true
                }
            }
            liveData.observe(owner) { wrapper ->
                wrapper?.takeIf { !it.isConsumed }?.let {
                    observer(it.value)
                    it.isConsumed = true
                }
            }
        }
    }

    // 事件包装类，用于标记事件是否已被消费
    private class EventWrapper<T>(
        val value: T,
        val isStickyEvent: Boolean,
        var isConsumed: Boolean = false
    )
}